package cn.changeforyou.web.nutz.common.security;

import cn.changeforyou.utils.cons.DateTimeUtils;
import cn.changeforyou.utils.pojo.BeanCopierUtil;
import cn.changeforyou.web.blog.po.User;
import cn.hutool.core.bean.BeanUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author XWY
 * @md-model springboot.springSecurity.jwt JwtToken生成的工具类 JWT token的格式：header.payload.signature header的格式（算法、token的类型）： {"alg": "HS512","typ": "JWT"}
 * payload的格式（用户名、创建时间、生成时间）： {"sub":"wang","created":1489079981393,"exp":1489684781} signature的生成算法： HMACSHA512(base64UrlEncode(header) + "."
 * +base64UrlEncode(payload),secret)
 */
@IocBean
public class JwtTokenUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);

    @Inject
    private SecurityConfig securityConfig;

    /**
     * 从token中获取JWT中的负载
     */
    public Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                .setSigningKey(securityConfig.getSecret())
                .parseClaimsJws(token)
                .getBody();
        } catch (Exception e) {
            LOGGER.info("JWT格式验证失败:{}", token);
        }
        return claims;
    }

    public String generateTokenFromUser(User user) {
        Map<String, Object> claims = BeanUtil.beanToMap(user, false, true);
        if(null != user.getCreateTime()) {
            claims.put("createTime", DateTimeUtils.DATE_TIME_STANDARD_FORMATER.format(user.getCreateTime()));
        }


        return generateToken(claims);
    }

    /**
     * 从token中获取登录用户名
     */
    public String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 从token获取用户
     *
     * @param token
     * @return
     */
    public User getUserFromToken(String token) {
        try {
            Claims claimsFromToken = getClaimsFromToken(token);
            User user = BeanUtil.toBean(claimsFromToken, User.class);
            return user;
        } catch (Exception e) {
           throw new AuthException("验证失败, 请重新登录");
        }

    }

    /**
     * 负责生成JWT的token
     */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
            .setClaims(claims)
            .setExpiration(generateExpirationDate())
            .signWith(SignatureAlgorithm.HS512, securityConfig.getSecret())
            .compact();
    }

    /**
     * 判断token是否已经失效
     */
    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }

    /**
     * 生成token的过期时间
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + securityConfig.getExpiration() * 1000);
    }

    /**
     * 从token中获取过期时间
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }
}
